package loveqq.niceexcel.converter.internal.string;

import cn.hutool.core.util.StrUtil;
import loveqq.niceexcel.annotation.internal.Internal;
import loveqq.niceexcel.converter.CellData;
import loveqq.niceexcel.converter.ConvertContext;
import loveqq.niceexcel.converter.Converter;
import loveqq.niceexcel.util.DateUtils;
import loveqq.niceexcel.util.NumberUtils;
import org.apache.poi.ss.usermodel.CellType;

import java.math.BigDecimal;
import java.text.ParseException;

/**
 * @author zhongjh@tsintergy.com
 * @date 2022-08-18
 */
@Internal
public class StringNumericConverter implements Converter<String> {
    @Override
    public Class<String> supportJavaType() {
        return String.class;
    }

    @Override
    public CellType supportExcelType() {
        return CellType.NUMERIC;
    }

    @Override
    public String convertToJavaData(CellData<?> cellData, ConvertContext context) {
        if (cellData.getDateValue() != null) {
            return DateUtils.format(cellData.getDateValue(), context.getDateTimeFormat());
        }
        if (cellData.getNumberValue() != null) {
            return NumberUtils.format(cellData.getNumberValue(), context.getNumberFormat());
        }
        return null;
    }

    @Override
    public CellData<?> convertToExcelData(String data, ConvertContext context) throws ParseException {
        if (StrUtil.isEmpty(data)) {
            return new CellData<>((BigDecimal) null);
        }
        if (context.getDateTimeFormat() != null) {
            return new CellData<>(DateUtils.parseDate(data, context.getDateTimeFormat()));
        }
        return new CellData<>(new BigDecimal(data));
    }

}
